use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use signal_hook::consts::signal::SIGINT;
use signal_hook::flag::register;

/**
 * 系统信号处理器，捕获Ctrl+C(SIGINT)信号
 */
pub struct Keyboard {
    ctrl_c_pressed: Arc<AtomicBool>,
}

impl Keyboard {
    pub fn new() -> Keyboard {
        let ctrl_c_pressed = Arc::new(AtomicBool::new(false));
        let pressed_ref = ctrl_c_pressed.clone();
        
        // 注册SIGINT(Ctrl+C)信号处理器
        register(SIGINT, pressed_ref).expect("无法注册信号处理器");

        Keyboard { ctrl_c_pressed }
    }

    /// 检查是否收到Ctrl+C信号
    pub fn is_ctrl_c_pressed(&self) -> bool {
        self.ctrl_c_pressed.load(Ordering::Relaxed)
    }

    /// 重置Ctrl+C状态
    pub fn reset_ctrl_c_state(&self) {
        self.ctrl_c_pressed.store(false, Ordering::Relaxed);
    }
}
